import { useReducer } from 'react'

const initData = [
  { name: '小满(只)', price: 100, count: 1, id: 1, isEdit: false },
  { name: '中满(只)', price: 200, count: 1, id: 2, isEdit: false },
  { name: '大满(只)', price: 300, count: 1, id: 3, isEdit: false }
]
type List = typeof initData
const reducer = (state: List, action: { type: string; id: number }) => {
  const payload = state.find((item) => item.id === action.id)
  switch (action.type) {
    case 'add':
      if (payload) {
        payload.count++
      }
      return [...state]
    case 'sub':
      if (payload) {
        payload.count--
      }
      return [...state]
    default:
      return state
  }
}

function Reducer() {
  const [list, dispatch] = useReducer(reducer, initData)
  return (
    <>
      <h1>购物车</h1>
      <table
        border={1}
        cellPadding={10}
        cellSpacing={0}
        width={600}
        style={{ margin: '0 auto' }}
      >
        <thead>
          <tr>
            <th>商品</th>
            <th>单价</th>
            <th>数量</th>
            <th>总价</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          {list.map((item) => (
            <tr key={item.id}>
              <td>{item.name}</td>
              <td>{item.price}</td>
              <td>
                <button onClick={() => dispatch({ type: 'add', id: item.id })}>
                  +
                </button>
                {item.count}
                <button onClick={() => dispatch({ type: 'sub', id: item.id })}>
                  -
                </button>
              </td>
              <td>{item.price * item.count}</td>
              <td>
                <button>删除</button>
                <button>编辑</button>
              </td>
            </tr>
          ))}
        </tbody>
        <tfoot>
          <tr>
            <td colSpan={4}>总价</td>
            <td>
              {list.reduce((total, item) => total + item.price * item.count, 0)}
            </td>
          </tr>
        </tfoot>
      </table>
    </>
  )
}

export default Reducer
